﻿using Loogn.OrmLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TaskCaller.Commons.Quartz;
using TaskCaller.Models;
using TaskCaller.Models.entity;
using TaskCaller.Repositories;

namespace TaskCaller.Services
{
    public class TimedTaskService
    {
        private readonly ITimedTaskRepository _timedTaskRepository;
        public TimedTaskService(ITimedTaskRepository timedTaskRepository)
        {
            _timedTaskRepository = timedTaskRepository;
        }


        public ResultObject Edit(TimedTask m)
        {
            if (string.IsNullOrEmpty(m.Url))
            {
                return new ResultObject("url不能为空");
            }
            if (string.IsNullOrEmpty(m.Cron))
            {
                return new ResultObject("cron表达不能为空");
            }
            try
            {
                var exp = new CronExpression(m.Cron);
            }
            catch
            {
                return new ResultObject("cron表达式不正确");
            }

            if (m.Id > 0)
            {
                m.UpdateTime = DateTime.Now;
                var flag = _timedTaskRepository.Update(m);
                return new ResultObject(flag);
            }
            else
            {
                m.LastExecTime = new DateTime(1900, 1, 1);
                var flag = _timedTaskRepository.Add(m);
                return new ResultObject(flag);
            }
        }

        public OrmLitePageResult<TimedTask> SearchList(string name, bool? enable, int pageIndex, int pageSize)
        {
            return _timedTaskRepository.SearchList(name, enable, pageIndex, pageSize);
        }

        public TimedTask SingleById(long id)
        {
            return _timedTaskRepository.SingleById(id);
        }

        public List<TimedTask> SelectByIds(List<long> ids)
        {
            return _timedTaskRepository.SelectByIds(ids);
        }


        public ResultObject Delete(long id)
        {
            var flag = _timedTaskRepository.Delete(id);
            return new ResultObject(flag);
        }

        public Dictionary<string, List<long>> SelectReadyList()
        {
            return _timedTaskRepository.SelectReadyList();
        }

        public int ExecuteOne(TimedTask task)
        {
            task.LastExecTime = DateTime.Now;
            return _timedTaskRepository.ExecuteOne(task);
        }

    }
}
